<template>
  <a-spin :loading="loading" class="mt-40 w-full">
    <GiChart height="360px" :option="chartOption"></GiChart>
  </a-spin>
</template>

<script setup>
import { useChart } from '@/hooks'
import dayjs from 'dayjs'
import { momentStatisticsGraphData } from '@/apis'
import { graphDataChartOptionBar } from './data'
import { totalDataO } from './data.js'
import { formatObject } from '@/utils/common'

defineOptions({ name: 'largeCircleScreenChart' })

const chartOptionO = ref(graphDataChartOptionBar)

const props = defineProps(['commonParam', 'selectValue'])
const loading = ref(false)

const getData = async () => {
  try {
    loading.value = true
    const param = {
      startAt: dayjs(props.commonParam.startAt).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      endAt: dayjs(props.commonParam.endAt).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
      momentId: props.commonParam.momentId,
      type: props.selectValue
    }
    const res = await momentStatisticsGraphData(param)
    const result = JSON.stringify(res.data) === '{}' ? [] : res.data.data
    const xData = []
    const yData = []
    result.forEach((item) => {
      xData.push(item.keyAsString)
      yData.push(item.docCount)
    })
    const graphDataChartOptionBarO = JSON.parse(JSON.stringify(graphDataChartOptionBar))
    graphDataChartOptionBarO.title.text = formatObject(totalDataO, 'type', props.selectValue, 'label')
    graphDataChartOptionBarO.xAxis.data = xData
    graphDataChartOptionBarO.series.data = yData
    chartOptionO.value = graphDataChartOptionBarO
  } finally {
    loading.value = false
  }
}

watch(
  () => [props.commonParam, props.selectValue],
  () => {
    getData()
  },
  {
    deep: true,
    immediate: true
  }
)

const { chartOption } = useChart(() => {
  return chartOptionO.value
})

defineExpose({ getData })
</script>
